package com.bonjour.work.config;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;

import com.bonjour.common.helper.EncryptHelper;
import com.bonjour.common.helper.SpringHelper;
import com.bonjour.common.view.IWebAuthenticationFilter;
import com.bonjour.common.view.parser.RequestSession;


public class WebAuthenticationFilter implements IWebAuthenticationFilter {
    private final ApplicationContext context;

    private static final String GET = "GET";

    private static final String POST = "POST";

    private static final String USER_LOGIN_URI = "/user/login";

    private static final String USER_REGISTER_URI = "/user/registry";

    WebAuthenticationFilter(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public boolean authentication(RequestSession session, HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-Signature");
//        if ("dev".equals(SpringHelper.applicationEnv())) {
//            session.uid = "300";
//            session.tid = "300";
//            return true;
//        }
        if (USER_LOGIN_URI.equals(request.getRequestURI())
                || USER_REGISTER_URI.equals(request.getRequestURI())) {
            LOG.info("接口{}、{}拦截器放行！", USER_LOGIN_URI, USER_REGISTER_URI);
            return true;
        }

        if (null != session.signature && !"".equals(session.signature)) {
            List<String> jwts = EncryptHelper.verifyJWT(session.signature);
            //  tid | uid | workId
            session.tid = Long.parseLong(jwts.get(0));
            session.uid = Long.parseLong(jwts.get(1));
            session.ext = jwts.get(2);
            return true;
        }

        LOG.info("调用的uri为 ：{}", request.getRequestURI());

        return false;
    }
}
